/*
 * SteepTimer - A timer designed for tea fanatics
 * Copyright (C) 2011  Wesley Crossman
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "CsvParser.h"
#include <qDebug>
#include <cassert>

CsvParser::CsvParser(QObject *parent, bool columnHeaders, bool trimSpaces, QChar fieldSep) : QObject(parent),
            m_columnHeaders(columnHeaders),
            m_trimSpaces(trimSpaces),
            m_fieldSep(fieldSep) {
}

int CsvParser::columnIndex(const QString &title) {
    assert(m_columnHeaders);
    return m_data[0].indexOf(title);
}

const QString &CsvParser::cell(QString column, int row) {
    int index = columnIndex(column);
    assert(index != -1);
    return m_data[row][index];
}

const QString &CsvParser::cell(int column, int row) {
    return m_data[row][column];
}

void CsvParser::parse(const QString &string) {
    const QChar quote('"'), rowsep('\n');
    QString src = string;
    src.replace("\r\n", "\n"); //for simplification
    src += '\n'; //appending newline so row closes
    bool inQuote = false, quotedField = false;
    QStringList row;
    QString cell;
    for (int a=0;a<src.length();++a) {
        bool isQuote = src[a] == quote;
        if (isQuote && inQuote && src[a+1] == quote) {
            //* append quote
            cell += quote;
        } else if (isQuote && inQuote) {
            //* end quote
            inQuote = false;
        } else if (isQuote) {
            //* start quote
            inQuote = true;
            quotedField = true;
        } else if (src[a] == m_fieldSep && !inQuote) {
            //* next field
            if (m_trimSpaces && !quotedField) cell = cell.trimmed();
            row.append(cell);
            cell.clear();
            quotedField = false;
        } else if (src[a] == rowsep && !inQuote) {
            //* next row
            if (!row.length() && !cell.length()) continue; //skip empty lines
            if (m_trimSpaces && !quotedField) cell = cell.trimmed();
            row.append(cell);
            cell.clear();
            quotedField = false;
            m_data.append(row);
            row.clear();
        } else {
            //* add to string
            cell += src[a];
        }
    }
}
